<script>
import basepath from '../../plugins/base.js'
import add from './add.vue'
import edit from './edit.vue'

export default {
  data() {
    return {
      imgbase: '',
      loading: false,
      pageIndex: 1,  //当前的 页码
      pageSize: 10,   //每页条数
      totalNum: 0,   //总数量
      autoHide: false,  //当只有一页数据时是否隐藏分页
      search: {
        name: ''
      },
      tableData: [],    //数据
      multipleSelection: [],  //选中的数据

      specs: [],
      form: {
        tid: 1,
        images: '',
        name: '',
        content: '',
        price: 0,
        unit: '杯',
        use_property: true,
        property: [
          {
            gskid: 1,  //规格 主键表  GoodSpecKey  id
            values: [],
            checked: true
          },
          {
            gskid: 2,
            values: [],
            checked: true
          },
          {
            gskid: 3,
            values: [],
            checked: true
          }
        ]
      },


      dialogAddVisible: false,
      dialogEditVisible: false
    }
  },
  methods: {
    //获取数据data
    getTableData() {
      this.loading = true;
      this.axios({
        method: 'get',
        url: 'Goods',
        params: { page: this.pageIndex, size: this.pageSize, name: this.search.name },
        data: {}
      }).then(response => {
        console.log('response: ', response);
        this.tableData = response.data;
        this.totalNum = response.count;

        setTimeout(() => {
          this.loading = false;
        }, 200);

      })
    }
    //复选框选中
    , handleSelectionChange(val) {
      this.multipleSelection = val;
    }
    //删除
    , del(id) {
      console.log('id: ', id);
      //axios  删除
      this.$message({
        type: 'success',
        message: '删除成功!'
      });


    }
    // 批量删除
    , batchDel() {
      if (this.multipleSelection.length > 0) {
        let ids = this.multipleSelection.reduce((p, v) => p + v.userID + ',', '');
        ids = ids.substr(0, ids.length - 1);

        let names = this.multipleSelection.reduce((p, v) => p + v.name + ',', '');
        names = names.substr(0, names.length - 1);

        this.$confirm('此操作将永久删除【' + names + '】信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          //axios  删除
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });



      }
      else
        this.$message({ type: 'warning', message: '请选择需要删除的用户信息！' })
    }
    //分页
    , handleCurrentChange(val) {
      this.pageIndex = val;
      this.getTableData();
    }
    //切换每页数量
    , handleSizeChange(val) {
      this.pageSize = val;
      this.getTableData();
    }

    //添加弹窗
    , add() {
      this.dialogAddVisible = true;
    }
    //添加保存
    , addSave() {
      //处理得到的数据
      let jsondata = JSON.parse(JSON.stringify(this.form));
      console.log('jsondata: ', jsondata);

      //1.判断是否开启属性
      if (!this.form.use_property)
        jsondata.property = []  //清空需要提交的属性数据

      //2.移除掉不需要的属性
      jsondata.property = jsondata.property.filter(v => v.checked == true);

      //3.讲属性值转换成 id
      jsondata.property.map(k => {
        //循环迭代 值
        k.values = k.values.map(v => {
          return this.specs.filter(s => s.id == k.gskid)[0].SpecValue.filter(sv => sv.value == v)[0].id;
        })
        return k;
      })
      console.log('jsondata ', jsondata);

      this.axios({
        method: 'post',
        url: 'Goods',
        data: jsondata
      }).then(response => {
        if (response.code > 0) {
          this.$message.success(response.msg);
          this.dialogAddVisible = false;
          this.getTableData();
        } else {
          this.$message.error(response.msg);
        }
      });
    },
    // 
    addClose() {
      //this.$message('弹窗关闭');
    }

    //修改弹窗
    , edit(val) {
      console.log('val: ', val);

      //处理得到的数据
      let jsondata = JSON.parse(JSON.stringify(val));
      jsondata.property.map(k => {
        //循环迭代 值  处理空值
        k.values = k.values == null ? [] : k.values;
        return k;
      })
      this.form = jsondata;


      this.dialogEditVisible = true;
    }
    //修改保存
    , editSave() {
      //处理得到的数据
      let jsondata = JSON.parse(JSON.stringify(this.form));

      //1.判断是否开启属性
      if (!this.form.use_property)
        jsondata.property = []  //清空需要提交的属性数据

      //2.移除掉不需要的属性
      jsondata.property = jsondata.property.filter(v => v.check == true);

      //3.讲属性值转换成 id
      jsondata.property.map(k => {
        //循环迭代 值
        k.values = k.values.map(v => {
          return this.specs.filter(s => s.id == k.gskid)[0].SpecValue.filter(sv => sv.value == v)[0].id;
        })
        return k;
      })
      this.axios({
        method: 'put',
        url: 'Goods/' + this.form.id,
        data: jsondata
      }).then(response => {
        if (response.code > 0) {
          this.$message.success(response.msg);
          this.dialogEditVisible = false;
          this.getTableData();
        } else {
          this.$message.error(response.msg);
        }
      });
    },

  },
  created() {
    this.imgbase = basepath.imgurl;
    this.getTableData();


    this.axios({
      method: 'get',
      url: 'Spec'
    }).then(response => {
      this.specs = response;
    });
  },
  components: {
    add, edit
  }
}
</script>

<template>
  <div>
    <!-- <img alt="Vue logo" src="/src/assets/logo.png">
    <el-image :src="'/src/assets/logo.png'" fit="fill" :lazy="true"></el-image> -->

    <!-- 表单搜索操作栏 -->
    <el-form :inline="true" :model="search" class="demo-form-inline"
      size="mini">
      <el-form-item>
        <el-button type="success" @click="add">添加</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="batchDel">修改</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="batchDel">批量删除</el-button>
      </el-form-item>

      <el-form-item>
        <el-input v-model="search.name" placeholder="姓名"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getTableData">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格数据 -->
    <el-table ref="multipleTable" :data="tableData" v-loading="loading"
      tooltip-effect="dark" style="width: 100%"
      @selection-change="handleSelectionChange">

      <el-table-column type="expand">
        <template #default="scope">
          <el-col :span="8" v-for="item in scope.row.property"
            :key="item.gskid">
            {{ item.name }}
            <ul>
              <li v-for="pp in item.values" :key="pp">
                {{ pp }}</li>
            </ul>
          </el-col>
        </template>
      </el-table-column>

      <el-table-column type="selection" width="55">
      </el-table-column>

      <el-table-column prop="id" label="编号" width="55">
      </el-table-column>

      <el-table-column prop="images" label="图片">
        <template #default="scope">
          <!--  :preview-src-list="srcList" -->
          <!-- <el-image style="width: 100px; height: 100px"
            :src="imgbase+ scope.row.images">
          </el-image> -->
          <el-avatar :src="imgbase+ scope.row.images"></el-avatar>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="商品">
      </el-table-column>

      <el-table-column prop="content" label="描述" show-overflow-tooltip>
      </el-table-column>

      <el-table-column prop="price" label="价格">
      </el-table-column>

      <el-table-column prop="typename" label="类型">
      </el-table-column>

      <el-table-column label="操作" width="220">
        <template #default="{row}">
          <!-- 删除气泡提示 -->
          <el-popconfirm confirm-button-text='好的' cancel-button-text='不用了'
            icon="el-icon-info" icon-color="red"
            :title="'确定删除【'+row.name+'】的信息吗？'" @confirm="del(row.userID)"
            @cancel="$message('已取消删除')">
            <template #reference>
              <el-button type="danger" size="mini"
                icon="el-icon-delete"></el-button>
            </template>
          </el-popconfirm>
          &nbsp;
          <el-button type="warning" size="mini" icon="el-icon-edit"
            @click="edit(row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <!-- 分页 -->
    <el-pagination @current-change="handleCurrentChange"
      @size-change="handleSizeChange" :hide-on-single-page="autoHide"
      :page-sizes="[5, 10, 20,,50, 100]" :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="totalNum"
      background>
    </el-pagination>

    <!-- 添加的弹窗 -->
    <el-dialog title="添加商品" :visible.sync="dialogAddVisible" width="80%"
      @close="addClose">
      <!-- 添加 -->
      <add :form="form"></add>
      <span slot="footer">
        <el-button @click=" dialogAddVisible= false">取消</el-button>
        <el-button type="primary" @click="addSave">保存</el-button>
      </span>
    </el-dialog>

    <!-- 修改的弹窗 -->
    <el-dialog title="修改商品信息" :visible.sync="dialogEditVisible" width="80%">

      <!-- 修改 -->
      <edit :form="form"></edit>
      <span slot="footer">
        <el-button @click=" dialogEditVisible= false">取消</el-button>
        <el-button type="primary" @click="editSave">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style>
</style>